package com.nmgs.util;

import com.nmgs.entity.Constants;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpClientUtils {
    /**
     * 发送SOAP请求并获取响应
     * @param data 查询类型
     * @param data2 JSON格式查询参数
     * @param url 服务端URL
     * @return 响应JSON字符串
     * @throws Exception 请求异常
     */
    public static String postParameters(String data, String data2, String queryUrl) throws Exception {
        // 1. 构建SOAP请求体
        String soapXml = buildSoapRequest(data, data2);

        // 2. 创建HTTP连接
        URL url = new URL(queryUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 3. 配置请求
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        connection.setRequestProperty("SOAPAction", ""); // 如果服务端需要则填写具体值
        connection.setDoOutput(true);

        // 4. 发送请求
        try (OutputStream os = connection.getOutputStream()) {
            os.write(soapXml.getBytes("UTF-8"));
        }

        // 5. 获取响应
        if (connection.getResponseCode() == 200) {
            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }
        } else {
            throw new RuntimeException("SOAP请求失败，HTTP状态码: " + connection.getResponseCode());
        }

        // 提取JSON响应部分
//        return extractJsonResponse(response);
    }

    private static String buildSoapRequest(String data, String data2) {
        return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                "xmlns:web=\"http://interFace.webService.nmgs.com/\">" +
                "<soapenv:Header/>" +
                "<soapenv:Body>" +
                "<web:GetWebServiceData>" +
                "<arg0>" + data + "</arg0>" +
                "<arg1>" + data2 + "</arg1>" +
                "</web:GetWebServiceData>" +
                "</soapenv:Body>" +
                "</soapenv:Envelope>";
    }

    private static String postSoapRequest(String url, String soapRequest) throws IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        // 设置请求头
        post.setHeader("Content-Type", "text/xml; charset=UTF-8");
        post.setEntity(new StringEntity(soapRequest, Constants.CHARSET_UTF8));

        // 配置超时设置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(Constants.DEFAULT_CONN_TIMEOUT)
                .setSocketTimeout(Constants.DEFAULT_READ_TIMEOUT)
                .build();
        post.setConfig(config);

        // 执行请求并获取响应
        try (CloseableHttpResponse response = client.execute(post)) {
            HttpEntity entity = response.getEntity();
            try (InputStream inputStream = entity.getContent();
                 BufferedReader reader = new BufferedReader(
                         new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            }
        }
    }

    private static String extractJsonResponse(String response) {
        if (response.contains("{") && response.contains("}")) {
            return StringEscapeUtils.unescapeHtml4(
                    response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1)
            );
        }
        return "";
    }
}
